package com.example.finalproject;

import com.example.finalproject.User.User;
import com.example.finalproject.car.Car;
import com.example.finalproject.car.CarService;
import com.example.finalproject.collection.CollectionService;
import com.example.finalproject.order.Order;
import com.example.finalproject.order.OrderService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import static com.example.finalproject.collection.CollectionController.carList;
import static com.example.finalproject.collection.CollectionController.collectionList;

@Controller
public class ProjectController {
    @Autowired
    private CollectionService collectionService;
    @Autowired
    private CarService carService;
    @Autowired
    private OrderService orderService;
    //header跳转
    //首页的跳转控制
    @RequestMapping("/toIndex")
    public String toIndex(){
        return "index";
    }
    //订单跳转控制
    @RequestMapping("/toOrder")
    public String toOrder(Model model, HttpServletRequest request){
        HttpSession session = request.getSession();
        User order_User = (User) session.getAttribute("login_User");

        // 空值检查
        if(order_User != null) {
            Order order = orderService.selectOrderByUserName(order_User.getUserName());
            if(order != null) {
                String order_CarId = order.getCarId();
                if(order_CarId != null) {
                    Car order_Car = carService.selectCarById(order_CarId);
                    if(order_Car != null) {
                        //将保存的汽车对象传递给前端订单页面显示
                        model.addAttribute("order_Car", order_Car);
                        return "order";
                    } else {
                        // 处理汽车对象为空的情况
                    }
                } else {
                    // 处理订单汽车ID为空的情况
                }
            } else {
                // 处理订单为空的情况
            }
        } else {
            // 处理订单用户为空的情况
        }
        // 默认返回一个错误页面或者其他处理
        model.addAttribute("error_Order","你的订单空空如也，别看啦！");
        return "index";
    }
    //收藏页跳转控制
    @RequestMapping("/toCollection")
    public String toCollection(Model model){
        carList.clear();
        collectionList.clear();
        collectionList = collectionService.findAllCollection();
        //遍历收藏列表，获取列表中每个id对应的汽车信息添加到car列表中
        for(int i = 0;i<collectionList.size(); ++i){
            String temporary_carId = collectionList.get(i).getCarId();
            Car temporary_car = carService.selectCarById(temporary_carId);
            carList.add(temporary_car);
        }
        model.addAttribute("carList", carList);
        return "collection";
    }


}
